<template>
<!-- 收益明细 -->
  <el-row>
    <el-col :span="24" style="margin-top: 20px">
      <el-card style="margin-top: 20px">
        <el-row type="flex" justify="space-around" style="align-items: center">
          <el-col style="font-weight: bold; font-size: 30px"
            >累计收益<i
              class="el-icon-view"
              style="margin-left: 50px"
              @click="shownum"
            ></i
          ></el-col>
          <el-col style="font-size: 30px"
            >{{ show ? asset.cumulative_profit : "****" }}元</el-col
          >
        </el-row>
      </el-card>

      <el-card style="margin-top: 20px">
        <el-row
          type="flex"
          justify="space-between"
          slot="header"
          class="clearfix"
          style="text-align: left"
        >
          <div style="text-align: left"><span>收益明细</span></div>
          <div style="text-align: right">
            <el-dropdown trigger="click" style="font-size: 18px">
              <span class="el-dropdown-link">
                时间<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item index="1" @click.native="changetable(90)"
                  >全部（近三个月）</el-dropdown-item
                >
                <el-dropdown-item index="2" v-on:click.native="changetable(30)"
                  >近一个月</el-dropdown-item
                >
                <el-dropdown-item index="3" @click.native="changetable(7)"
                  >近一周</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-row>
        <el-table
          :data="
            tabledata.slice(
              (currentPage - 1) * pagesize,
              currentPage * pagesize
            )
          "
          @selection-change="handleCurrentChange"
          cell-style="text-align:center;font-size:20px"
          header-cell-style="text-align:center"
          :row-class-name="tableRowClassName"
          :default-sort="{prop: 'profitIdate', order: 'descending'}"
        >
          <el-table-column
            v-for="(val, key) in tablelable"
            :key="key"
            :prop="key"
            :label="val"
            :sortable="true"
          ></el-table-column>
        </el-table>

        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
          :page-size="pagesize"
          :current-page.sync="currentPage"
        >
        </el-pagination>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card style="margin-top: 20px">
        <div slot="header" class="clearfix" style="text-align: left">
          <span>测试曲线图（后端）</span>
        </div>
        <div ref="chart" style="width: 500px; height: 300px"></div>
        <el-row type="flex" justify="space-around">
          <el-button @click="drawchart(30)">近一个月</el-button>
          <el-button @click="drawchart(90)">近三个月</el-button>
          <el-button @click="drawchart(180)">近六个月</el-button>
          <el-button @click="drawchart(365)">近一年</el-button>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
import * as echarts from "echarts";
import { getAllAssetsAPI } from "@/api/getAllAssetsAPI";
import { getAllMyProfitDetailsAPI } from "@/api/getAllMyProfitDetailsAPI";
export default {
  data() {
    return {
      // 资产配置对象
      asset: {
        cumulative_profit: (9999.0).toFixed(2),
      },
      // 数字可见性
      show: true,
      // 表格数据，收益明细对象
      tabledata: [],
      // 表头
      tablelable: {
        profitIdate: "日期",
        amount_change: "收益",
      },
      // 分页器有关数据
      total1: 0, //总条数
      pagesize: 6, //每页的条数
      currentPage: 1, //默认开始页面
    };
  },
  computed: {
    total() {
      return Math.min(this.total1,90);
    },
  },
  methods: {
    // 切换数字可见性
    shownum() {
      if (this.show) this.show = false;
      else this.show = true;
    },
    // 设置表格行类名
    tableRowClassName({ row, rowIndex }) {
      if (row.amount_change > 0) return "positive-row";
      if (row.amount_change < 0) return "native-row";
      else return "zero-row";
    },
// 画折线图
    drawchart(val) {
      echarts.dispose(this.$refs.chart)
      var myChart = echarts.init(this.$refs.chart);
      var datahold = [];

      for (let i = 0; i < Math.min(val,this.tabledata.length); i++) {
        var item = this.tabledata[i];
        var day = [item.profitIdate, item.cumulative_profit];
        datahold.push(day);
      }
      // console.log(datahold)
      var option = {
        xAxis: {
          name: "日期",
          type: "category",
        },
        yAxis: {
          name: "缺陷个数",
        },
        series: [
          {
            name: "累计收益",
            data: datahold.reverse(),
            type: "line",
          },
        ],
        tooltip: {
          trigger: "item", // axis   item   none三个值
        },
      };
      myChart.setOption(option);
    },
    // 切换表格页码
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
    },
    // 切换表格总数
    changetable(day) {
      this.total1 = Math.min(day,this.tabledata.length);
      if(day==7){
        this.pagesize=7
      }else{
        this.pagesize=6
      }
      this.currentPage = 1;
    },
    // 获取资产配置对象
    async getAllAssets(){
      console.log("发送getAllAssets请求");
      const { data: res } = await getAllAssetsAPI(this.$route.query.user_id);
      if (res.flag) {

        var list = this.$jsonToObj(res);
        this.asset = list[0];

      }
    },
    async getProfitDetails(){
      const {data:res} = await getAllMyProfitDetailsAPI(this.$route.query.user_id)
      if(res.flag){
        this.$message.success('获取收益明细列表成功！')
          var list = this.$jsonToObj(res);
          for(let i=0;i<list.length;i++){
            list[i].profitIdate = this.formatDate(list[i].profitIdate)
          }
          this.tabledata=list
          this.tabledata.sort(
            this.sortby('profitIdate')
          ).reverse()
          this.total1=this.tabledata.length
      }
    },
    sortby(props){
      return function(a,b){
        return b[props]-a[props]
      }
    },
    formatDate(time){
      var date = new Date(time);
      var year = date.getFullYear(),
          month = date.getMonth()+1,//月份是从0开始的
          day = date.getDate(),
          hour = date.getHours(),
          min = date.getMinutes(),
          sec = date.getSeconds();
      var newTime = year + '-' +
                  (month < 10? '0' + month : month) + '-' +
                  (day < 10? '0' + day : day)
      return newTime;         
    }
  },

  created() {
    this.getAllAssets();
    this.getProfitDetails()
  },

  watch:{
      tabledata(){
          this.drawchart(Math.min(365,this.total1))
      }
  }

  
};
</script>

<style>
.el-table .positive-row {
  background: #ff3333;
}

.el-table .native-row {
  background: #66dd00;
}
.el-table .zero-row {
  background: #fdf5e6;
}
</style>
